﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


using NguyenHoa.Web.App_Code;
using NguyenHoa.Domains;
using NguyenHoa.Services;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxClasses;

namespace NguyenHoa.Web.Admin
{
  public partial class ProductList : AdminBasePage
  {
    #region Properties
    private string m_innerError = string.Empty;
    private string ERROR0001 = "error:insert|";
    private string ERROR0002 = "error:update|";
    private string ERROR0003 = "error:delete|";

    internal override int RequiredPermission
    {
      get
      {
        return (int)FunctionList.Product;
      }
    }
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack && !IsCallback)
      {
        LoadList();
      }

      if (gvList.IsCallback)
      {
        LoadList();
      }
    }

    protected void gvList_CustomJSProperties(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewClientJSPropertiesEventArgs e)
    {
      e.Properties["cpInnerError"] = m_innerError;
    }

    protected void gvList_CellEditorInitialize(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewEditorEventArgs e)
    {
      switch (e.Column.FieldName)
      {
        case "CreatedDate":
          e.Editor.Enabled = false;
          if (gvList.IsNewRowEditing)
          {
            e.Editor.Value = DateTime.Now;
          }

          break;
        case "CreatedBy":
          e.Editor.Enabled = false;
          if (gvList.IsNewRowEditing)
          {
            e.Editor.Value = CurrentUser.Username;
          }

          break;
        case "ModifiedDate":
          e.Editor.Enabled = false;
          if (gvList.IsEditing)
          {
            e.Editor.Value = DateTime.Now;
          }

          break;
      }
    }

    protected void gvList_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
      if (e.Parameters.StartsWith("filter"))
      {
        LoadList();
      }
    }

    protected void gvList_CommandButtonInitialize(object sender, ASPxGridViewCommandButtonEventArgs e)
    {
      if (!CanDelete && e.Button.ButtonType == ColumnCommandButtonType.Delete)
      {
        e.Visible = false;
      }
      if (!CanModify && e.Button.ButtonType == ColumnCommandButtonType.Edit)
      {
        e.Visible = false;
      }
      if (!CanModify && e.Button.ButtonType == ColumnCommandButtonType.New)
      {
        e.Visible = false;
      }
    }

    protected void gvList_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
    {
      int Id = 0;
      int.TryParse(e.Keys["Id"].ToString(), out Id);
      Delete(Id);
      SetStateGrid(sender, e);
    }

    protected void gvList_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
      string name = string.Empty;
      if (e.NewValues["Name"] != null)
        name = e.NewValues["Name"].ToString();
      Insert(name);
      SetStateGrid(sender, e);
    }

    protected void gvList_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
    {
      int id = 0;
      string name = string.Empty;
      int.TryParse(e.Keys["Id"].ToString(), out id);
      if (e.NewValues["Name"] != null)
        name = e.NewValues["Name"].ToString();
      Update(id, name);
      SetStateGrid(sender, e);
    }
    #endregion

    #region Methods
    private void LoadList()
    {
      gvList.DataSource = new ProductService().GetAll();
      gvList.DataBind();
    }

    private void Insert(string name)
    {
      #region Check parameters
      if (string.IsNullOrEmpty(name))
      {
        m_innerError = ERROR0001 + string.Format(Resources.Messages.ERR0007, Resources.Strings.Name);
        return;
      }
      #endregion

      #region Save DB
      try
      {
        Product p = new Product();
        p.Name = name;
        p.ModifiedDate = p.CreatedDate = DateTime.Now;
        p.CreatedBy = p.ModifiedBy = CurrentUser.Username;
        new ProductService().Save(p);
      }
      catch (Exception e)
      {
        WriteLog("ProductList::Insert ProductList.aspx", e);
        m_innerError = ERROR0001 + Resources.Messages.ERR0004;
      }
      #endregion
    }

    private void Update(int id, string name)
    {
      #region Check parameters
      if (id == 0)
      {
        m_innerError = ERROR0002 + Resources.Messages.ERR0003;
        return;
      }

      if (string.IsNullOrEmpty(name))
      {
        m_innerError = ERROR0002 + string.Format(Resources.Messages.ERR0007, Resources.Strings.Name);
        return;
      }
      #endregion

      #region Save DB
      try
      {
        ProductService ps = new ProductService();
        Product p = ps.GetById(id);
        p.Name = name;
        p.ModifiedBy = CurrentUser.Username;
        p.ModifiedDate = DateTime.Now;
        ps.Update(p);
      }
      catch (Exception ex)
      {
        WriteLog("Product::Update Product.aspx", ex);
        m_innerError = ERROR0002 + Resources.Messages.ERR0004;
      }
      #endregion
    }

    private void Delete(int id)
    {
      #region Check parameters
      if (id == 0)
      {
        m_innerError = ERROR0003 + Resources.Messages.ERR0060;
        return;
      }
      #endregion

      #region Save DB
      try
      {
        TList<ProductLocale> plist = new ProductLocaleService().GetByProductId(id);
        new ProductService().DeleteAllById(id);
      }
      catch (Exception ex)
      {
        WriteLog("Product.aspx::Delete Product", ex);
        m_innerError = ERROR0003 + Resources.Messages.ERR0060;
      }
      #endregion
    }

    private void SetStateGrid(object sender, System.ComponentModel.CancelEventArgs e)
    {
      ASPxGridView gv = sender as ASPxGridView;
      e.Cancel = true;
      gv.CancelEdit();
      LoadList();
    }
    #endregion
  }
}
